import uix
import uiutil
import xtriui
import blue
import util
import base
import os
import uthread
import listentry
import audio2
import uicls
import uiconst
from service import *
BTNSIZE = 16

class InsiderSoundPlayer(uicls.Window):
    __guid__ = 'form.InsiderSoundPlayer'
    __neocommenuitem__ = (('Sound Player', 'InsiderSoundPlayer'),
     True,
     ROLE_GML)

    def ApplyAttributes(self, attributes):
        uicls.Window.ApplyAttributes(self, attributes)
        (w, h,) = (200, 300)
        self.HideClippedIcon()
        self.HideMainIcon()
        self.SetTopparentHeight(0)
        self.SetMinSize([w, h])
        self.SetHeight(h)
        self.SetCaption('Sound Player')
        margin = const.defaultPadding
        self.sr.innermain = uicls.Container(name='inner', left=margin, top=margin, parent=self.sr.main, pos=(0, 0, 0, 0))
        self.sr.bottomframe = uicls.Container(name='bottom', align=uiconst.TOBOTTOM, parent=self.sr.innermain, height=BTNSIZE, left=margin, top=margin, clipChildren=1)
        self.sr.main = uicls.Container(name='main', align=uiconst.TOALL, parent=self.sr.innermain, pos=(margin,
         margin,
         margin,
         margin))
        uicls.Frame(parent=self.sr.innermain, color=(1.0, 1.0, 1.0, 0.2), idx=0)
        uicls.Frame(parent=self.sr.main, color=(1.0, 1.0, 1.0, 0.2), idx=0)
        self.node = None
        self.InitButtons()
        self.InitScroll()



    def CloseX(self, *args):
        self.Close()



    def InitButtons(self):
        buttons = [['Play',
          self.SoundPlay,
          '38_228'], ['Stop',
          self.StopAllSounds,
          '38_111']]
        for button in buttons:
            (hint, function, iconID,) = button
            btn = uicls.Container(name=hint, align=uiconst.TOLEFT, width=BTNSIZE, left=const.defaultPadding, parent=self.sr.bottomframe)
            uicls.Frame(parent=btn, color=(1.0, 1.0, 1.0, 0.125))
            icon = uicls.Icon(icon=iconID, parent=btn, size=BTNSIZE)
            icon.OnClick = function
            icon.hint = hint
            icon.autoPos = uix.AUTOPOSCENTER
            icon.OnMouseEnter = (self.ShowSelected, 1)
            icon.OnMouseExit = (self.ShowSelected, 0)
            icon.sr.hilite = uicls.Fill(parent=btn, name='hilite', align=uiconst.TOALL, state=uiconst.UI_HIDDEN)

        textWidth = 353
        self.textBlock = uicls.Container(parent=self.sr.bottomframe, align=uiconst.TOLEFT, width=textWidth, left=const.defaultPadding)
        self.textTop = uicls.Label(text='', parent=self.textBlock, align=uiconst.TOALL, left=(int((textWidth * 0.2)) + const.defaultPadding), top=1, height=0, fontsize=10, letterspace=1, linespace=9, uppercase=1, state=uiconst.UI_NORMAL, autowidth=False, autoheight=False)
        self.textBtm = uicls.Label(text='', parent=self.textBlock, align=uiconst.TOALL, left=const.defaultPadding, height=0, top=1, fontsize=10, letterspace=1, linespace=9, uppercase=1, state=uiconst.UI_NORMAL, autowidth=False, autoheight=False)



    def ShowSelected(self, toggle, btn, *args):
        btn.sr.hilite.state = [uix.UI_HIDDEN, uix.UI_DISABLED][toggle]



    def SoundPlay(self, *args):
        if (self.node != None):
            sm.StartService('audio').SendUIEvent(self.node.filename)



    def StopAllSounds(self, *args):
        audio2.StopAll()



    def GetFileListFromDirectories(self):
        soundFolder = 'res/audio/'
        soundUrlList = []
        for each in os.listdir(soundFolder):
            if (('.txt' in each) and (each != 'Init.txt')):
                self.ParseTxtFile((soundFolder + each), soundUrlList)

        for e in soundUrlList:
            yield e




    def ParseTxtFile(self, file, soundUrlList):
        bf = blue.os.CreateInstance('blue.ResFile')
        if not bf.Open(file):
            raise RuntimeError(('Unable to open sound file %s' % file))
        myData = bf.Read()
        bf.Close()
        lines = myData.split('\r\n')
        if (lines == None):
            return 
        lines = lines[1:]
        for line in lines:
            if (len(line) <= 0):
                break
            entries = line.split('\t')
            if (len(entries) < 3):
                continue
            entry = entries[2].strip()
            if (entry.startswith('music_') == False):
                soundUrlList.append((entry, file))




    def InitScroll(self):
        self.scroll = uicls.Scroll(parent=self.sr.main, padding=(const.defaultPadding,
         const.defaultPadding,
         const.defaultPadding,
         const.defaultPadding))
        sounds = []
        for sound in self.GetFileListFromDirectories():
            sounds.append(listentry.Get('Generic', {'label': sound[0],
             'hint': sound[1],
             'filename': sound[0],
             'OnClick': self.ScrollClick,
             'OnDblClick': self.ScrollDblClick}))

        self.scroll.Load(contentList=sounds, headers=['Filename'], fixedEntryHeight=18)



    def ScrollClick(self, node, *args):
        self.node = node.sr.node



    def ScrollDblClick(self, node, *args):
        self.node = node.sr.node
        self.SoundPlay()




